//
//  ZDDMusicParser.m
//  QQ音乐(皇家尊享版)
//
//  Created by 周冬冬 on 16/7/20.
//  Copyright © 2016年 我的mac. All rights reserved.
//

#import "ZDDMusicParser.h"
#import "NSDateFormatter+shared.h"

@implementation ZDDMusicParser
+(NSArray<ZDDLynic *> *)parserLyricFilename:(NSString *)filename{

    NSString * filePath = [[NSBundle mainBundle] pathForResource:filename ofType:nil];
    
    NSString * str = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:nil];

    //分割字符串
    NSArray * lyricArr = [str componentsSeparatedByString:@"\n"];
    
    


    //解析
    NSRegularExpression * expression = [NSRegularExpression regularExpressionWithPattern:@"\\[[0-9]{2}:[0-9]{2}.[0-9]{2}\\]" options:0 error:nil];

    //创建可变数组
    NSMutableArray * tempArr = [NSMutableArray array];

    //遍历每一句
    for (NSString * onelyric in lyricArr) {
        NSArray * results = [expression matchesInString:onelyric options:0 range:NSMakeRange(0, onelyric.length)];
        //取得最后一个字符串的范围
        NSTextCheckingResult * lastResult = results.lastObject;
        //歌词的截取
        NSString * content = [onelyric substringFromIndex:lastResult.range.location + lastResult.range.length];
        
        for (NSTextCheckingResult * result in results) {
            
            //创建模型
            ZDDLynic * lyric = [[ZDDLynic alloc] init];
            
            //截取时间字符串
            NSString * timeStr = [onelyric substringWithRange:NSMakeRange(result.range.location, result.range.length)];
            
            NSTimeInterval timeinterval = [self timeintervalWithTimeStr:timeStr];
            lyric.initialTime = timeinterval;
            //设置歌词内容
            lyric.content = content;
            
            //添加到可变数组
            [tempArr addObject:lyric];
            
        }
    }
    //进行排序 根据时间间隔
    
    NSSortDescriptor * descriptor = [NSSortDescriptor sortDescriptorWithKey:@"initialTime" ascending:YES];
    NSArray * lyricModels = [tempArr sortedArrayUsingDescriptors:@[descriptor]];
    return lyricModels;
}

//将时间转成时间间隔

+(NSTimeInterval)timeintervalWithTimeStr:(NSString *)str{

    //创建时间格式对象
    NSDateFormatter * dateformatter = [NSDateFormatter shareManger];
    //设置时间格式
    dateformatter.dateFormat = @"[mm:ss:SS]";
    //转换时间对象
    NSDate * targetDate = [dateformatter dateFromString:str];
    //创建出事时间的对象
    NSDate * initDate = [dateformatter dateFromString:@"[00:00:00]"];
    //计算时间间隔
    return [targetDate timeIntervalSinceDate:initDate];


}

@end
